package com.xca.gsondemo.views;

import android.app.AlertDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;
import com.xca.gsondemo.R;
import com.xca.gsondemo.utils.ImageDownloader;
import com.xca.gsondemo.utils.JsonUtils;
import com.xca.gsondemo.utils.URLExtractor;

import java.util.List;

public class BookFragment extends Fragment {
    private View bookFragment ;
    private ImageView bImg , bToJd , bToDd , bToSn ;
    private TextView bName  , bReader , bTime , bType , bItr , bMore ;
    private AsyncTask downloadImageTask ;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (bookFragment == null){
            bookFragment = inflater.inflate(R.layout.book , container , false) ;
        }
        init();
        showMessage();

        return bookFragment ;
    }


    private void  showMessage() {
        //获取图片路径
        String imgUri = getValueByKey("book.json" , "img") ;
        Log.d("图片链接", imgUri);

        //eg:1 error
//        new ImageDownloader(getActivity()).execute(imgUri);

        //eg:5 error
//        new ImageSaver(bImg, getActivity()).execute(imgUri);
//        File file = new File(getContext().getCacheDir(), "image.jpg");
//        if (file.exists()) {
//            Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
//            bImg.setImageBitmap(bitmap);
//        }re
        //eg:2 error 展示的图片是R.drawable.book
        Glide.with(this)
                .load(imgUri)
                .into(bImg);

        //eg:3 error
//        Picasso.get()
//                .load(imgUri)
//                .into(bImg);
        
        //eg:4 error
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                try {
//                    URL url = new URL(imgUri);
//                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//                    connection.setDoInput(true);
//                    connection.connect();
//                    InputStream inputStream = connection.getInputStream();
//                    Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
//                    bImg.post(new Runnable() {
//                        @Override
//                        public void run() {
//                            bImg.setImageBitmap(bitmap);
//                        }
//                    });
//                } catch (Exception e){
//                    e.printStackTrace();
//                }
//            }
//        }).start();

        //获取书名
        String bookName = getValueByKey("book.json" , "title");
        bName.setText(bookName);
        //获取阅读人数
        String bookReader = getValueByKey("book.json" , "reading");
        bReader.setText(bookReader);
        //获取发布时间
        String bookTime = getValueByKey("book.json" , "bytime");
        bTime.setText(bookTime);
        //获取书籍类型
        String bookType = getValueByKey("book.json" , "catalog");
        bType.setText(bookType);
        //获取书籍描述
        String bookItr1 = getValueByKey("book.json" , "tags");
        String bookItr2 = getValueByKey("book.json" , "sub2");
        bItr.setText(TextUtils.substring(bookItr1 + "\n" + bookItr2, 0,
                Math.min(50, (bookItr1 + "\n" + bookItr2).length())) + "...");
        bMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onMoreClicked();
            }
        });
        //获取网址
        String bookIntent = getValueByKey("book.json" , "online");
        List<String> uris = URLExtractor.extractUrls(bookIntent);
        String uri1 = uris.get(0);
        String uri2 = uris.get(1);
        String uri3 = uris.get(2);
        Log.d("网址", uri1 + uri2 + uri3);
        bToJd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openWebsite(uri1);
            }
        });
        bToDd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openWebsite(uri2);
            }
        });
        bToSn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openWebsite(uri3);
            }
        });
    }

    private String  getValueByKey(String name , String key) {
        String jsonStr = getJson(name);
        String value = JsonUtils.getKeyRecursively(jsonStr, key);
        Log.d("asdf", "getValueByKey value ==== " + value);
        return value ;
    }

    private String getJson(String name) {
        String json = JsonUtils.getJsonFromAssets(getActivity(), name);
        Log.d("asdf", "getJson = " + json);
        return json;
    }



    //跳转浏览器
    private void openWebsite(String uri) {
        String url = uri; // 替换成你要跳转的网址
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        if (intent.resolveActivity(getContext().getPackageManager()) != null) {
            startActivity(intent);
        } else {
            // 没有可以处理此Intent的应用程序
            Toast.makeText(getActivity(), "无法打开网页，请检查设备是否安装了浏览器", Toast.LENGTH_SHORT).show();
        }
    }

    //查看更多
    private void onMoreClicked() {
        String bookItr2 = getValueByKey("book.json" , "sub2");
        new AlertDialog.Builder(getContext())
                .setTitle("书籍详细介绍")
                .setMessage(bookItr2)
                .setPositiveButton(android.R.string.ok, null)
                .show();
    }

    private void init(){
        bImg = bookFragment.findViewById(R.id.book_img);
        bName = bookFragment.findViewById(R.id.book_name);
        bReader = bookFragment.findViewById(R.id.book_reader);
        bTime = bookFragment.findViewById(R.id.book_time) ;
        bType = bookFragment.findViewById(R.id.book_type) ;
        bItr = bookFragment.findViewById(R.id.book_itr) ;
        bMore = bookFragment.findViewById(R.id.tvMore);
        bToJd = bookFragment.findViewById(R.id.to_jd) ;
        bToDd = bookFragment.findViewById(R.id.to_dd) ;
        bToSn = bookFragment.findViewById(R.id.to_sn) ;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        bookFragment = null ;
    }
}
